package com.server.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.server.service.ICommonDataService;
import com.server.service.IEmailSettingService;

@Service("EmailSettingService")
public class EmailSettingService implements IEmailSettingService {
	
	private static final String TABLE_NAME = "reward.org_mail";
	private static final String VIEW_NAME = "reward.v_org_mail";
	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private ICommonDataService commonDataService;
	
	@Override
	public Boolean update(String operator,String id, Map<String, Object> inputMap) {
		return commonDataService.update(operator, TABLE_NAME, "Id", id, inputMap);
	}
	
	@Override
	public Boolean changeState(String id,Integer state){
		String sql = "Update %s set Valid=%s where Id=%s";
		return jdbcTemplate.update(String.format(sql, TABLE_NAME,state,id))>0;
	}

	@Override 
	public List<Map<String, Object>> getList(){
		String sql = "select * from %s order by Id asc";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, VIEW_NAME));
		return list;
	}

	@Override
	public Map<String, Object> getForm(String id) {
		return commonDataService.getFormData(VIEW_NAME, "Id", id, null, null);
	}
	
	/**
	 * 发送邮件
	 * @param type
	 * @param count,待处理的条数
	 * @param recievers
	 * @author ServerZhang
	 * @date 2017年3月14日
	 */
	@Override
	public void sendEmail(Integer type,Integer count,List<String> recievers) {
		
		String sql = "select * from %s where TypeNo=%s and Valid=1";
		List<Map<String, Object>> list = jdbcTemplate.queryForList(String.format(sql, TABLE_NAME,type));
		if (list.size() <= 0) {
			return;
		}
		Map<String, Object> map = list.get(0);
		Object mailObj = map.get("MailUser");
		Object pswObj = map.get("Password");
		Object smtpObj = map.get("SMTP");
		Object titleObj = map.get("Title");
		Object contentObj = map.get("Content");
		Object receiveObj = map.get("Receive");
		Object urlObj = map.get("ProjectUrl");
		if (mailObj==null||pswObj==null||smtpObj==null) {
			return;
		}
		String projectUrl = urlObj==null ? "" : urlObj.toString();
		if (!projectUrl.startsWith("http://")) {
			projectUrl = "http://" + projectUrl;
		}
		String mailUser = mailObj.toString();
		String psw = pswObj.toString();
		String smtp = smtpObj.toString();
		List<String> _receivers = new ArrayList<String>();//收款邮箱
		
		String title = null;
		String content = null;
		switch (type) {
		case 1:
			title = "通知财务按时打款: ";
			content = "有 <span style='color:red;'>"+count+"</span> 条新的返费申请，请您及时处理。</br>";
			break;
		case 2:
			title = "通知审核人员处理审核请求: ";
			content = "有 <span style='color:red;'>"+count+"</span> 条新的审核申请，请您及时处理。</br>";
			break;
		case 3:
			title = "通知收款人查看返费详细: ";
			content = "您有一笔新的返费，感谢您为公司做出的卓越贡献。</br>";
			break;

		default:
			break;
		}
		//添加收件人
		if (type == 3) {
			_receivers.addAll(recievers);
		}else {
			if(receiveObj == null) return;
			String[] split = receiveObj.toString().split("[,，]");
			for(String str : split){
				_receivers.add(str);
			}
		}
		
		if (titleObj!=null) {
			title += titleObj.toString();
		}
		if (contentObj!=null) {
			content += contentObj.toString();
		}
		Iterator<String> iterator = _receivers.iterator();
		while(iterator.hasNext()){
			String receiver = iterator.next();
			this.send(projectUrl,mailUser,psw,smtp,title,content,receiver);
		}
	}
	public void send(String projectUrl,String mailUser,
			String psw,String smtp,String title,
			String content,String receiver){
		// 配置发送邮件的环境属性
        final Properties props = new Properties();
        /*
         * 可用的属性： mail.store.protocol / mail.transport.protocol / mail.host /
         * mail.user / mail.from
         */
        // 表示SMTP发送邮件，需要进行身份验证
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", smtp);
        // 发件人的账号
        props.put("mail.user", mailUser);
        // 访问SMTP服务时需要提供的密码
        props.put("mail.password", psw);

        // 构建授权信息，用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 用户名、密码
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        // 使用环境属性和授权信息，创建邮件会话
        Session mailSession = Session.getInstance(props, authenticator);
        // 创建邮件消息
        MimeMessage message = new MimeMessage(mailSession);
        // 设置发件人
        InternetAddress form;
		try {
			form = new InternetAddress(
			        props.getProperty("mail.user"));
			message.setFrom(form);
			// 设置收件人
			InternetAddress to = new InternetAddress(receiver);
			message.setRecipient(RecipientType.TO, to);
			
			// 设置抄送
			/* InternetAddress cc = new InternetAddress("994359398@qq.com");
        message.setRecipient(RecipientType.CC, cc);*/
			
			// 设置密送，其他的收件人不能看到密送的邮件地址
			/*InternetAddress bcc = new InternetAddress("aaaaa@163.com");
        message.setRecipient(RecipientType.CC, bcc);*/
			// 设置邮件标题
			message.setSubject(title);
			
			// 设置邮件的内容体
			message.setContent(content+"&nbsp;&nbsp;<a href='"+projectUrl+"'>[点击查看更多]</a>", "text/html;charset=UTF-8");
			
			// 发送邮件
			Transport.send(message);
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
}
